<script>
export default {
  name: "GrowthRecord",
  data(){
    return{
      babyId:0,
      showFlag:false,
      recordData:[],
      title:'',
      dialogFormVisible:false,
      form:{},
      flag:false,
    }
  },
  methods:{
    saveForm(){
      const fd=new FormData
      Object.keys(this.form).forEach(key=>{
        fd.append(key,this.form[key])
      })
      if (this.flag){
        this.$axios.post('growth/update',fd).then(resp=>{
          if (resp.data){
            alert('修改成功')
            this.changeBaby(this.babyId)
            this.handleClose()
          }else {
            alert('修改失败')
            this.changeBaby(this.babyId)
            this.handleClose()
          }
        })
      }else {
        this.$axios.post('growth/add',fd).then(resp=>{
          if (resp.data){
            alert('添加成功')
            this.changeBaby(this.babyId)
            this.handleClose()
          }else {
            alert('添加失败')
            this.changeBaby(this.babyId)
            this.handleClose()
          }
        })
      }
    },
    handleClose(){
      this.form={}
      this.dialogFormVisible=false
    },
    add(){
      this.title='添加成长记录'
      this.form.babyId=this.babyId
      this.flag=false
      this.dialogFormVisible=true
    },
    updateAge(){
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1;
      const day = currentDate.getDate();

      this.recordData.forEach(record=>{
        const parts = record.date.split("-");

        record.year=year-parseInt(parts[0])
        record.month=month-parseInt(parts[1])
        record.day=day-parseInt(parts[2])

        // 处理天数为负数的情况
        if (record.day < 0) {
          const tempDate = new Date(year, month, 0);
          const daysInMonth = tempDate.getDate();
          record.day = daysInMonth - parseInt(parts[2]) + day;
          record.month--;
        }

        // 处理月数为负数的情况
        if (record.month < 0) {
          record.year--;
          record.month = 12 + record.month;
        }
        console.log(record)
      })
      console.log(`当前日期：${year}-${month}-${day}`);
    },
    update(record){
      this.title='修改成长记录'
      this.form.id=record.id
      this.form.babyId=this.babyId
      this.form.date=record.date
      this.form.height=record.height
      this.form.weight=record.weight
      this.form.discribe=record.discribe
      this.form.headCircumference=record.headCircumference
      this.flag=true
      this.dialogFormVisible=true
    },
    del(id){
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post('/growth/del?id='+id).then(resp=>{
          if(resp.data){
            this.changeBaby(this.babyId)
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }else {
            this.$message({
              type: 'error',
              message: '删除失败，请联系管理员！'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    changeBaby(babyId){
      this.babyId=babyId
      if (babyId!==0){
        this.$axios.get("growth/list?id="+babyId).then(resp=>{
          this.recordData=resp.data
          this.updateAge()
        })
        this.showFlag=true
      }else {
        this.showFlag=false
      }
    },
  },
  created() {
  }
}
</script>

<template>
<div>
  <div v-if="!showFlag">
    <el-card shadow="always">
      请选择您的宝宝
    </el-card>
  </div>
  <el-button type="primary" @click="add" v-if="showFlag">添加</el-button>
  <div class="mainuse" v-if="showFlag">
    <div>
      <el-card shadow="hover" style="width: 98%; height: auto" v-for="record in recordData">
        <div slot="header" class="clearfix">
          <span>{{record.date}}</span>&nbsp;&nbsp;&nbsp;
          <span v-if="record.year>0">{{record.year}}年</span>
          <span v-if="record.month>0">{{record.month}}个月</span>
          <span v-if="record.day>0">{{record.day}}天</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="del(record.id)">删除</el-button>
          <el-button style="float: right; padding: 3px 0" type="success" @click="update(record)">修改</el-button>
          <br><br>
          <span style="color: #42b983">{{record.discribe}}</span>
        </div>
        <div>
          <span>身高：<span style="color: #42b983">{{record.height}}</span> cm</span>
          <span>体重：<span style="color: #42b983">{{record.weight}}</span> kg</span>
          <span>头围：<span style="color: #42b983">{{record.headCircumference}}</span> cm</span>
        </div>
      </el-card>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form :model="form">
        <el-form-item label="身高">
          <el-input @input="$forceUpdate()" type="number" v-model="form.height" auto-complete="off" style="width: 90%" placeholder="请输入身高（单位cm）"></el-input>
        </el-form-item>
        <el-form-item label="体重">
          <el-input @input="$forceUpdate()" type="number" v-model="form.weight" auto-complete="off" style="width: 90%" placeholder="请输入体重（单位kg）"></el-input>
        </el-form-item>
        <el-form-item label="头围">
          <el-input @input="$forceUpdate()" type="number" v-model="form.headCircumference" auto-complete="off" style="width: 90%" placeholder="请输入头围（单位cm）"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input @input="$forceUpdate()" v-model="form.discribe" auto-complete="off" style="width: 90%" placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item label="日期：">
          <el-col :span="11" style="width: 300px" >
            <el-date-picker @input="$forceUpdate()" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder="选择日期" v-model="form.date" style="width: 100%;"></el-date-picker>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="saveForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</div>
</template>

<style scoped>
.mainuse{
  margin-top: 10px;
  padding-left: 10px;
  column-count: 3;
  column-gap: 0;
  margin-bottom: 150px;
}
</style>
